<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * adds extra access checks, dependent on page state
 */
class DirPage {

	private $alerter;
	private $db_access;
	private $access_manager;
	
	public function __construct() {
		$this->alerter = new Alerter();
		$this->db_access = new DbAccessor();
		$this->access_manager = new AccessManager();
	}

	function page_inc_check_access($page) {
		$this->access_manager->check_access("READ");
	}

	function page_inc_execute_action($page, $action) {
		$THISDIR = $page->directory_tree[$page->dir_depth - 1];

		switch($action) {
			case "markread":
				if (!$_SESSION['user_id']) {
					errorpage(6);
				}
				$from = array("ITEM_IN INNER JOIN SUB_IN ON ITEM_IN.sub_id = SUB_IN.sub_id", "DUMMY");
				$where = "SUB_IN.dir_id = {$THISDIR['dir_id']}";
				$sql = $this->db_access->db_query_select(array(array(), "ITEM_IN.item_id"), $from, $where);
				$sqlresult = $this->db_access->db_do_query($sql);
				$values = array();
				while ($r = $this->db_access->db_fetch_array($sqlresult))
					array_push($values, array($r['item_id'], $_SESSION['user_id']));
				if (count($values)) {
					$sql = $this->db_access->db_query_insert_multiple(array(item_id, user_id), $values, "HAS_READ", 1);
					$this->db_access->db_do_query($page, $sql);
					$n = $this->db_access->db_affected_rows();
					$page->menu[$THISDIR['dir_id']]['new_items'] = 0;
					$page->menu[$THISDIR['dir_id']]['read_items'] += $n;
				}
				$this->alerter->add_alert("alles gelezen hier...");
				break;
			case "ignore":
				if (!$_SESSION['user_id']) {
					errorpage(6);
				}
				$sql = $this->db_access->db_query_insert(array('dir_id', 'user_id'), array($THISDIR['dir_id'], $_SESSION['user_id']), "IGNORE_DIR");
				$db_access->db_do_query($page, $sql);
				$this->alerter->add_alert("directory '{$THISDIR['title']}' wordt vanaf nu genegeerd");
				$page->menu[$THISDIR['dir_id']]['ignored'] = 1;
				break;
			case "unignore":
				if (!$_SESSION['user_id']) {
					errorpage(6);
				}
				$sql = $this->db_access->db_query_delete("IGNORE_DIR", "dir_id = {$THISDIR['dir_id']} AND user_id = {$_SESSION['user_id']}");
				$this->db_access->db_do_query($page, $sql);
				$this->alerter->add_alert("directory '{$THISDIR['title']}' wordt vanaf nu niet meer genegeerd");
				$page->menu[$THISDIR['dir_id']]['ignored'] = 0;
				break;
			default:
				$this->alerter->add_alert("unknown action: $action");
				break;
		}
	}

	/**
	 * execute page logic
	 */
	function page_inc_execute($page) {

		// backwards compatible
		if ($_GET['subber']) {
			redirect("{$page->dir_path}/{$_GET['subber']}.subset");
		}
		
		global $CONFIG;
		$CONTENT = array();
		$THISDIR = $page->directory_tree[$page->dir_depth - 1];
		
		$CONTENT['title'] = $THISDIR['title']; 

		if ($THISDIR['show_items']) {

			$CONTENT['items'] = array();
		
			$where = "ITEM.item_type_id = ITEM_TYPE.item_type_id AND 
					  ITEM.item_id = ITEM_IN.item_id AND 
					  ITEM_IN.sub_id = SUB_IN.sub_id AND 
					  SUB_IN.dir_id = {$THISDIR['dir_id']} AND 
					  ITEM.author = M1.user_id AND 
					  ITEM.editor = M2.user_id AND 
					  NOT ITEM_IN.deleted AND 
					  NOT ITEM.deleted";

			$order = "sticky DESC, " . $THISDIR['sorting_sql'];
			if ($THISDIR['show_subsets']) 
				$order = "SUB_IN.sub_title ASC, $order";

			$sql = $this->db_access->db_query_select(array(array("*"), array("*"), array(), array("*"), array(), array(), 
										 "M1.nick as nick_author, M2.nick as nick_editor"), 
								   array("ITEM", "ITEM_TYPE", "ITEM_IN", "SUB_IN", "MEMBER AS M1", "MEMBER AS M2", "DUMMY"), 
								   $where, $order, $limit);

			$items = $this->db_access->db_do_query($sql);
			
			$read = array();

			if ($_SESSION['user_id']) {
				$readings = $this->db_access->db_do_query($this->db_access->db_query_select(array(array(), "HAS_READ.item_id"), 
										array("(((HAS_READ INNER JOIN ITEM ON HAS_READ.item_id = ITEM.item_id) INNER JOIN ITEM_IN ON HAS_READ.item_id = ITEM_IN.item_id) INNER JOIN SUB_IN ON ITEM_IN.sub_id = SUB_IN.sub_id)" . ($THISDIR['show_subsets'] ? " INNER JOIN SUBSET ON SUB_IN.sub_id = SUBSET.sub_id" : "")), 
										"SUB_IN.dir_id = {$THISDIR['dir_id']} AND user_id = {$_SESSION['user_id']}", $order, $limit));
				while ($item = $this->db_access->db_fetch_array($readings)) {
					$read[$item['item_id']] = 1;
				}
			}

			if ($THISDIR['show_subsets']) {
				$CONTENT['subsets']['visible'] = array();
			}

			while ($item = $this->db_access->db_fetch_array($items)) {
				if ($THISDIR['show_subsets'] and ($item['sub_id'] != $prev_sub)) {
					array_unshift($CONTENT['subsets']['visible'], array('sub_id' => $item['sub_id'], 'sub_title' => $item['sub_title']));
				}
				$item['unread'] = $_SESSION['user_id'] ? !$read[$item['item_id']] : 0;
				$item['new'] = (($item['edit'] > $_SESSION['member']['last_visit']) and $item['unread']) ? 1 : 0;
				array_unshift($CONTENT['items'], $item);
				$prev_sub = $item['sub_id'];
			}
			
			if ($THISDIR['show_subsets']) {
				$CONTENT['subsets']['all'] = array();
				if ($_SESSION['user_id']) {
					$readresult = $this->db_access->db_do_query($this->db_access->db_query_select(array(array(), "SUB_IN.sub_id, COUNT(HAS_READ.item_id) AS `reads`"),
										  array("(SUB_IN INNER JOIN ITEM_IN ON SUB_IN.sub_id = ITEM_IN.sub_id) INNER JOIN HAS_READ ON ITEM_IN.item_id = HAS_READ.item_id"), "SUB_IN.dir_id = {$THISDIR['dir_id']} AND user_id = {$_SESSION['user_id']} AND !ITEM_IN.deleted", "SUB_IN.sub_id ASC", "", "sub_id"));
					$reads = array();
					while ($r = $this->db_access->db_fetch_array($readresult)) {
						$reads[$r['sub_id']] = $r['reads'];
					}
				}
				$sql = $this->db_access->db_query_select(array(array(), 'SUBSET.body_id, SUB_IN.*, COUNT(ITEM_IN.item_id) AS items, 0 AS `reads`'), 
							array("(SUBSET INNER JOIN SUB_IN ON SUBSET.sub_id = SUB_IN.sub_id) LEFT JOIN ITEM_IN ON SUB_IN.sub_id = ITEM_IN.sub_id"), 
							"SUB_IN.dir_id = {$THISDIR['dir_id']} AND !ITEM_IN.deleted", "SUB_IN.sub_title ASC", "", "sub_id");
				$sqlresult = $this->db_access->db_do_query($sql);
				while ($s = $this->db_access->db_fetch_array($sqlresult)) {
					if ($_SESSION['user_id']) {
						$s['reads'] = $reads[$s['sub_id']];
					}
					if ($this->access_manager->has_access('MODERATE') || $this->access_manager->has_access('ADMIN')) {
						$s['editlink'] = "{$page->dir_path}/{$s['sub_id']}.edit_sub";
					}
					if ($s['items']) {
						array_unshift($CONTENT['subsets']['all'], $s);
					}
				}
			}
		}
			
		$page->content = $CONTENT;

		if ($_SESSION['user_id']) {
			
			$toolbox = new Toolbox();
			if ($THISDIR['show_items']) { // mark all items read
				$toolbox->add_action($page, 'markread', 'url-action', 'markread', '', 0);
			}
			if ($page->menu[$THISDIR['dir_id']]['children']) { // mark all items read
				$toolbox->add_action($page, 'markread-sub', 'url', "{$THISDIR['dir_id']}.fora?action=markread-sub");
			}
		
			// ignoring
			if (!$page->menu[$THISDIR['dir_id']]['ignored'])
				$toolbox->add_action($page, 'ignore', 'url-action', 'ignore');
			else
				$toolbox->add_action($page, 'unignore', 'url-action', 'unignore');
				
			// subscribing
			if (!$page->menu[$THISDIR['dir_id']]['subscription']) {
				$toolbox->add_action($page, 'subscribe_dir', 'popup', "{$page->dir_path}/.subscribe");
			} else {
				$toolbox->add_action($page, 'altersubscription_dir', 'popup', "{$page->dir_path}/.subscribe");
			}
				
			// adding
			if ($this->access_manager->has_any_add_access() && $THISDIR['show_items']) {
				$toolbox->add_action($page, 'add_item', 'url', '.add_item', '', 1);
			}
				
			// edit directory settings
			if ($this->access_manager->has_access("MODERATE") || $this->access_manager->has_access("ADMIN")) {
				$toolbox->add_action($page, 'edit_dir', 'url', '.edit_dir');
			}
		}
		
		$sql = $this->db_access->db_query_update(array('hits'), array('hits + 1'), "DIRECTORY", "dir_id = {$THISDIR['dir_id']}");
		$this->db_access->db_do_query($sql);

		$forum = new Forum();
		if ($THISDIR['show_subfora'] and is_array($page->menu[$THISDIR['dir_id']]['children']) and count($page->menu[$THISDIR['dir_id']]['children']))
			$page->subfora = $forum->fora_get_subfora($THISDIR['dir_id'], $page->menu);
		
	}


	/**
	 * dress up page content using skin stuff
	 */
	function page_inc_dress($page) {
		if ($page->directory_tree[$page->dir_depth - 1]['show_body']) {
			$page->content['body'] = $page->body_main; //TODO: remove silly workaround
			print_body($page); 
		}
		if ($page->directory_tree[$page->dir_depth - 1]['show_subsets'])
			print_subsetlist($page, $page->content['subsets']['all'], $page->content['subsets']['visible'], $page->dir_path, $_SESSION['user_id'] ? 1 : 0); //TODO: only pass $page

		if ($page->subfora)
			print_subfora($page, $page->subfora, $page->dir_path); //TODO: only pass $page
		
		if ($page->directory_tree[$page->dir_depth - 1]['show_items'])
			print_itemlist($page, $page->content['items'], $page->dir_path, $page->directory_tree[$page->dir_depth - 1]['crop_topiclist']); //TODO: only pass $page

	}
}

?>
